// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.unit.compiler;

import java.util.HashSet;
import java.util.Set;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class ConstructorLine {
  public enum Type {NEW_UNIT_CALL, OTHER};
  
  public Type type;
  public NewUnitCall newUnitCall;
  public String code;
  
  public ConstructorLine replaceLocalFieldAccess(Unit unit, NewUnitCall target) {
    String compiledCode = code;
    
    Set<String> constructorArgNames = new HashSet<String>();
    for (String argName : unit.constructorArgs.argNames) {
      constructorArgNames.add(argName);
    }
    
    for (FieldLine fieldLine : unit.fieldLines) {
      compiledCode = Regex.getThisFieldAccessPattern(fieldLine.name)
          .matcher(compiledCode)
          .replaceAll("this." + target.fieldName + "_$1");
    }
    for (FieldLine fieldLine : unit.fieldLines) {
      if (!constructorArgNames.contains(fieldLine.name)) {
        compiledCode = Regex.getFieldAccessPattern(fieldLine.name)
            .matcher(compiledCode)
            .replaceAll("this." + target.fieldName + "_$1");
      }
    }
    for (int i = 0; i < unit.constructorArgs.argNames.length; i++) {
      compiledCode = Regex.getFieldAccessPattern(unit.constructorArgs.argNames[i])
          .matcher(compiledCode)
          .replaceAll(target.unitArgs[i]);
    }
    
    ConstructorLine compiledLine = new ConstructorLine();
    compiledLine.type = ConstructorLine.Type.OTHER;
    compiledLine.code = compiledCode;
    return compiledLine;
  }
}
